package uds.geoloc;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import uds.data.HashMapRessources;
import uds.data.InformationRessource;
import uds.data.POI_Database;
import uds.data.POI_Entry;
import uds.data.UserPreference;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;

// RessourcesActivity est l'activité qui permet de trouver les ressources d'un type précis et de les classer par distance
public class RessourcesActivity extends Activity 
{
	// Initialisation des variables nécessaires
	private LocationManager position;
	private ArrayList<POI_Entry> entries = null;
	
	private String provider;
	
	private Location location;
	
    private List<String> listeRessources = new ArrayList<String>();
    
    private Context contextAct;
    
    private HashMapRessources sortie;
    
    private HashMap<String, InformationRessource> donnees;
	
    private POI_Database base_poi = new POI_Database(this);
    private UserPreference usr_pref ;
	
	private ListView listeResultats;
	
	private Button bouton = null ;
	
	private Spinner ressources ;
	
    private ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ressources);
        
        // Initialisation des composants
        bouton = (Button) findViewById(R.id.buttonPlan); 
		bouton.setOnClickListener(boutonListener);
        		
        contextAct = this.getApplicationContext();
        
        ressources = (Spinner) findViewById(R.id.spinnerRessources);
        listeResultats = (ListView)findViewById(R.id.listResultat);
        
        // Récupération du HashMap des ressources
        HashMapRessources.initialisationHashMapRessources(this);
        donnees = HashMapRessources.getHashMap();
        
        base_poi.open();
        listeRessources = base_poi.getListeRessources(); // Récupération de la liste des ressources
        
        usr_pref = new UserPreference(this);         
		       
        ressources.setAdapter(new MyAdapter(this, R.layout.spinnerperso, listeRessources));
        
        String context = Context.LOCATION_SERVICE;
        
        position = (LocationManager)getSystemService(context);
        // Récupération de la position de l'utilisateur
        if(usr_pref.getPreference(UserPreference.ATR_GEOLOCALISATION)=="oui"){
        	provider = LocationManager.GPS_PROVIDER;
        	location = position.getLastKnownLocation(provider);
        	System.out.println("GPS");
        }
        
        if(location!=null){
        	System.out.println("Position :");
        	System.out.println(location.getLatitude());
        	System.out.println(location.getLongitude());
        } else {
        	provider = LocationManager.NETWORK_PROVIDER; // Via le network si besoin
            location = position.getLastKnownLocation(provider);
        }
        
        // Implémentation d'un OnItemSelectedListener sur le spinner
        ressources.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() 
        {
			@Override
			public void onItemSelected(AdapterView<?> l, View view, int position, long id) 
			{
				base_poi.open(); 
				test.clear();
				// Récupération de la liste des POI du type sélectionné
			    entries = base_poi.getPOI_EntryWithType((String)l.getSelectedItem());
			         
			    for(POI_Entry entry : entries)
			    {
			      	double tmpLat = Double.parseDouble(entry.getLatitude());
			       	double tmpLon = Double.parseDouble(entry.getLongitude());
			       	
			       	// Récupération de la position du POI
			       	Location tmp = new Location(provider);
			       	tmp.setLatitude(tmpLat);
			       	tmp.setLongitude(tmpLon);
			        		
			       	float tmpDist = 0;
			       	if (location != null)
			       	{
			       		tmpDist = Math.round(tmp.distanceTo(location)) ; // Calcul de la distance à l'utilisateur
			       	}
			       	HashMap<String, String> tmpStockage = new HashMap<String, String>() ;
			       	if(base_poi.getPOI_EntryWithId(entry.getRelated_to_poi()) != null)
			       	{
			       		tmpStockage.put("id", entry.getId());
			       		tmpStockage.put("Batiment", base_poi.getPOI_EntryWithId(entry.getRelated_to_poi()).getName()); // Stockage du bâtiment lié
				       	if (entry.getFloor().equals("")){
				       	} else {
				       		tmpStockage.put("Etage", "Etage : "+entry.getFloor()); // Stockage de l'étage de la ressource	       		
				       	}
				       	if (location != null)
				       	{
				       		tmpStockage.put("dist", Float.toString(tmpDist));
				       		tmpStockage.put("Distance", "Distance : "+tmpDist+" mètres"); // Stockage de la distance
				       	}
				        	
				       	test.add((HashMap<String, String>) tmpStockage.clone());
			       	} else {
				       	
			       	}
			    }
			    if(location != null){
			    	Collections.sort(test, new HashMapComparator()); // Tri de la liste sur la distance
			    }
			    // Initialisation du ListView
			    SimpleAdapter mSchedule = new SimpleAdapter (contextAct, test, R.layout.listitem, new String[] {"Batiment", "Etage", "Distance"}, new int[] {R.id.batiment, R.id.etage, R.id.distance});        
			    listeResultats.setAdapter(mSchedule);
			    // Inialisation du OnItemClickListener sur le ListView
			    listeResultats.setOnItemClickListener(listeListener);
			        
			    base_poi.close();   
		    	
			}

			@Override
			public void onNothingSelected(AdapterView<?> l) 
			{
				
			}
         });
  
    }	
        //base_poi.close();
    
    // Initialisation de notre ListView spécial
    public class MyAdapter extends ArrayAdapter<String>
    {
    	private Context myContext;
    	
        public MyAdapter(Context context, int textViewResourceId,   List<String> listeRessources) {
            super(context, textViewResourceId, listeRessources);
            this.myContext = context;
        }
 
        @Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
 
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
        
        // Implémentation de la vue d'une ligne du ListView
        public View getCustomView(int position, View convertView, ViewGroup parent) {
 
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.spinnerperso, parent, false);
            TextView label=(TextView)row.findViewById(R.id.nomRessource);
            
            if(donnees.get(listeRessources.get(position)).getDisplay_name() == null){
            
            } else {
            	label.setText((CharSequence) donnees.get(listeRessources.get(position)).getDisplay_name());
            }
            
            ImageView icon=(ImageView)row.findViewById(R.id.imageRessource);
            if(donnees.get(listeRessources.get(position)).getId_drawable() == 0){

            } else {
            	icon.setImageResource((Integer) donnees.get(listeRessources.get(position)).getId_drawable());
            }			
            return row;
        }
        
    }
    
    // Implémentation du comparateur
    public class HashMapComparator implements Comparator
    {
    	public int compare ( Object object1 , Object object2 )
    	{
           	String obj1Value = (String)((HashMap<String,String>) object1).get("dist") ;
            String obj2Value = (String)((HashMap<String,String>) object2).get("dist") ;
            
            return obj1Value.compareTo ( obj2Value ) ;
        }
    }
    
    // Implémentation du OnClickListener
    private OnClickListener boutonListener = new OnClickListener() 
    {
    	@Override
    	public void onClick(View v) 
    	{
    		Intent intent = new Intent(RessourcesActivity.this, PlanActivity.class);
    		String tmp = new String();
    		Bundle extra = new Bundle();
    		if(entries.size()==0){
    			System.out.println("Fail !!");
    		}
    			
    		tmp = (String) entries.get(0).getType();

    		extra.putString("provenance", "Ressource1"); // Spécification de la provenance
    		extra.putString("type_ressource", tmp); // Spécification du type de ressource
    		
    		intent.putExtras(extra);
    		
    		startActivity(intent);
    	}
    };
    
    // Implémentation du OnItemClickListener
    private OnItemClickListener listeListener = new OnItemClickListener() {
		@Override
     	public void onItemClick(AdapterView<?> a, View v, int position, long id) {
			Intent intent = new Intent(RessourcesActivity.this, PlanActivity.class);
    		String tmp = new String();
    		Bundle extra = new Bundle();
    		    			
    		tmp = test.get(position).get("id");
    		extra.putString("provenance", "Ressource2"); // Spécification de la provenance
    		extra.putString("id", tmp); // Spécification de la ressource
    		
    		intent.putExtras(extra);
    		
    		startActivity(intent);
    	}
    };
        	
}